package com.easyfun.healthmagicbox.comm;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import android.util.Log;

public class HealthThreadPool extends ThreadPoolExecutor{
	
	// 线程池的参数corePoolSize 为核心线程；
	// maximunPoolSize为最大线程；
	// keepAliveTime为最长生命时间；
	// unit是其时间单位；
	// workQueue任务队列；
	// handler是过多线程之后的策略
	
	public HealthThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,    
            BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {    
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);    
    }    
    
    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();    
    private final AtomicLong numTasks = new AtomicLong();    
    private final AtomicLong totalTime = new AtomicLong();
	private String LOG_TAG = HealthThreadPool.class.getSimpleName();    
    
    protected void beforeExecute(Thread t, Runnable r) {    
        super.beforeExecute(t, r);    
        Log.v(LOG_TAG ,String.format("Thread %s: start %s", t, r));    
        startTime.set(System.nanoTime());    
    }    
    
    protected void afterExecute(Runnable r, Throwable t) {    
        try {    
            long endTime = System.nanoTime();    
            long taskTime = endTime - startTime.get();    
            numTasks.incrementAndGet();    
            totalTime.addAndGet(taskTime);    
            Log.v(LOG_TAG ,String.format("Thread %s: end %s, time=%dns", t, r, taskTime));    
        } finally {    
            super.afterExecute(r, t);    
        }    
    }    
    
    protected void terminated() {    
        try {    
        	Log.v(LOG_TAG ,String.format("Terminated: avg time=%dns", totalTime.get() / numTasks.get()));    
        } finally {    
            super.terminated();    
        }    
    }    
    
	
	//List<MyTask> tasks = Collections.synchronizedList(new ArrayList<MyTask>());

    private static HealthThreadPool instance = HealthThreadPool.getInstance();

    public static HealthThreadPool getInstance() {
        if (instance == null) {
            instance = new HealthThreadPool(5, 15, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),    
        	            new ThreadPoolExecutor.CallerRunsPolicy()); 
        }
        return instance;
    }
    
    @Override	
    public void execute(Runnable task)
    {
    	super.execute(task);
    }
}
